package com.ruoyi.activiti.command;

import com.ruoyi.activiti.service.IBizTodoItemService;
import org.activiti.bpmn.model.*;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.impl.bpmn.behavior.MultiInstanceActivityBehavior;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.*;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;
import org.springframework.util.CollectionUtils;
import java.util.Date;
import java.util.List;

//支持UserTask节点间互相跳转,包括普通UserTask和多实例UserTask
//不支持涉及并行网关的情形。
public class JumpTaskCommand implements Command {

    private String currentTaskId;//当前任务ID

    private String targetElementId;//目标活动元素ID

    private String assignee;//目标活动处理人

    private IBizTodoItemService todoItemService;//待办service

    public JumpTaskCommand(String currentTaskId, String targetElementId, String assignee, IBizTodoItemService todoItemService) {
        this.currentTaskId = currentTaskId;
        this.targetElementId = targetElementId;
        this.assignee = assignee;
        this.todoItemService = todoItemService;
    }

    @Override
    public Object execute(CommandContext commandContext) {
        //当前任务实体
        TaskEntity currentTaskEntity = commandContext.getTaskEntityManager().findById(currentTaskId);
        //获取当前执行实体
        ExecutionEntity execution = currentTaskEntity.getExecution();
        //获取任务管理器
        TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
        //获取目标活动元素
        Process process = ProcessDefinitionUtil.getProcess(currentTaskEntity.getProcessDefinitionId());
        UserTask targetElement = (UserTask) process.getFlowElement(targetElementId);
        String msg = "自由跳转到："+targetElement.getName();
        CommentEntity commentEntity = commandContext.getCommentEntityManager().create();
        commentEntity.setType("comment");
        commentEntity.setTime(new Date());
        commentEntity.setAction("AddComment");
        commentEntity.setMessage(msg);
        commentEntity.setFullMessage(msg);
        commentEntity.setProcessInstanceId(currentTaskEntity.getProcessInstanceId());
        //获取当前活动元素
        String currentElementId = execution.getActivityId();
        UserTask currentElement = (UserTask) process.getFlowElement(currentElementId);
        boolean flag = false;
        //判断当前活动元素是否多实例，删除所有子执行流，清除父执行流变量(如果业务需要，可以还原历史上该节点的变量)
        /*********************************当前节点为多实例时 ******************************************/
        if(currentElement.getBehavior() instanceof MultiInstanceActivityBehavior){
            flag = true;
            ExecutionEntity secondExecution = execution.getParent();
            execution = secondExecution;
            ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
            MultiInstanceLoopCharacteristics loopCharacteristics = currentElement.getLoopCharacteristics();
            if(loopCharacteristics == null){
                throw new RuntimeException("没有找到多实例");
            }
            ExecutionEntity finalExecution = execution;
            List<ExecutionEntity> executions = (List<ExecutionEntity>) execution.getExecutions();
            executions.forEach(item->{
                if(!finalExecution.getId().equals(item.getId())){
                    List<TaskEntity> itemTask = taskEntityManager.findTasksByExecutionId(item.getId());
                    commentEntity.setTaskId(itemTask.get(0).getId());
                    commandContext.getCommentEntityManager().insert(commentEntity);
                    commandContext.getHistoryManager().recordActivityEnd(item,msg);
                    todoItemService.deleteBizTodoItemByTaskId(itemTask.get(0).getId());
                    executionEntityManager.deleteChildExecutions(item,msg,false);
                    executionEntityManager.deleteExecutionAndRelatedData(item,msg,true);
                }
            });
            execution.removeVariables();
            execution.setMultiInstanceRoot(false);
            execution.setActive(true);
            /*********************************当前节点为多实例时 ******************************************/
        }else{
            //当前节点非多实例时
            //删除当前任务，第一个boolean为true表示删除历史记录，为false表示修改历史记录标记此任务结束；第二个boolean为true转发全局监听事件-活动已结束
            taskEntityManager.deleteTask(currentTaskEntity,msg,false,false);
            //插入comment批注
            commentEntity.setTaskId(currentTaskId);
            commandContext.getCommentEntityManager().insert(commentEntity);
            //结束当前活动
            commandContext.getHistoryManager().recordActivityEnd(currentTaskEntity.getExecution(),msg);
        }
        //设置签收人，多实例任务不用设置签收人
        if(!(targetElement.getBehavior() instanceof MultiInstanceActivityBehavior)){
            targetElement.setAssignee(assignee);
        }
        //设置下一个活动
        execution.setCurrentFlowElement(targetElement);
        Context.getAgenda().planContinueProcessInCompensation(execution);
        return null;
    }
}
